<template>
	<view class="page">
    <u-navbar :fixed="false" title="物料查询" :autoBack="true" bgColor="#fff"></u-navbar>
    <view class="search">
      <view class="search-type" @click="pickerType = 'type'">{{ form.typeName }}
        <u-icon name="arrow-down" size="24rpx"></u-icon>
      </view>
      <u-search
        placeholder="请输入"
        v-model="searchValue"
        @search="search"
        :showAction="false"
      ></u-search>
    </view>
    <view class="box" v-if="list.length">
      <u-icon name="arrow-left" :color="listIndex != 0 ?'#000':'#c8c9cc'" size="32rpx" @click="changeIndex(-1)"></u-icon>
      <view class="u-flex-1 u-text-center">{{ listIndex + 1 }} / {{ list.length }}</view>
      <u-icon name="arrow-right" :color="listIndex != list.length -1 ?'#000':'#c8c9cc'" size="32rpx" @click="changeIndex(1)"></u-icon>
    </view>
    <view v-if="list.length">
      <view class="goods-title">
        {{ listIndex + 1 }}.{{ list[listIndex].FmaterialName }}
        <view class="u-f-l-20"><u-icon name="photo" color="#2979ff" size="28" @click="imageBig(list[listIndex].FmaterialNumber)"></u-icon></view>
      </view>
      <view class="goods-info u-m-b-36">
        <view class="u-flex u-m-b-16">
          <view class="u-flex-1 form-info">
            <view class="form-lable">品牌</view>
            <view class="form-content">{{ list[listIndex].Brand }}</view>
          </view>
          <view class="u-flex-1 form-info">
            <view class="form-lable">编码</view>
            <view class="form-content">{{ list[listIndex].FmaterialNumber }}</view>
          </view>
        </view>
        <view class="u-flex u-m-b-16">
          <view class="u-flex-1 form-info">
            <view class="form-lable">商品属性(零售)</view>
            <view class="form-content">{{list[listIndex].Attributes}}</view>
          </view>
          <view class="u-flex-1 form-info">
            <view class="form-lable">规格</view>
            <view class="form-content">{{ list[listIndex].ModelName }}</view>
          </view>
        </view>
        <view class="u-flex u-m-b-16">
          <view class="u-flex-1 form-info">
            <view class="form-lable">库存单位</view>
            <view class="form-content">{{list[listIndex].UnitName}}</view>
          </view>
          <view class="u-flex-1 form-info">
            <view class="form-lable">计价单位</view>
            <view class="form-content">{{list[listIndex].priceUnit}}</view>
          </view>
        </view>
        <view class="u-flex u-m-b-16">
          <view class="u-flex-1 form-info">
            <view class="form-lable">零售价</view>
            <view class="form-content">{{ list[listIndex].RetailPrice }}</view>
          </view>
          <view class="u-flex-1 form-info">
            <view class="form-lable">单价</view>
            <view class="form-content">{{ list[listIndex].RetailPrice }}</view>
          </view>
        </view>
        <view class="u-flex u-m-b-16">
          <view class="u-flex-1 form-info">
            <view class="form-lable">现存量</view>
            <view class="form-content">{{ list[listIndex].ExistQty }}</view>
          </view>
          <view class="u-flex-1 form-info">
            <view class="form-lable">可用量</view>
            <view class="form-content">{{ list[listIndex].UseQty }}</view>
          </view>
        </view>
        <view class="u-flex u-m-b-16">
          <view class="u-flex-1 form-info">
            <view class="form-lable">包装量</view>
            <view class="form-content">{{ list[listIndex].FmaterialQty }}</view>
          </view>
          <view class="u-flex-1 form-info">
            <view class="form-lable">物料分组</view>
            <view class="form-content">{{ list[listIndex].FmaterialGroup }}</view>
          </view>
        </view>
        <view class="u-flex u-m-b-16">
          <view class="u-flex-1 form-info">
            <view class="form-lable">商品重量</view>
            <view class="form-content">{{ list[listIndex].FmaterialWeight }}</view>
          </view>
          <view class="u-flex-1 form-info">
            <view class="form-lable">采购员</view>
            <view class="form-content">{{ list[listIndex].PurChaser }}</view>
          </view>
        </view>
        <view class="u-flex u-m-b-16">
          <view class="u-flex-1 form-info">
            <view class="form-lable">商品描述</view>
            <view class="form-content">{{ list[listIndex].FmaterialDes }}</view>
          </view>
        </view>
        <u-line></u-line>
      </view>
    </view>
    <view class="box" style="display: block;" v-else>
      <u-empty></u-empty>
    </view>

    <view class="footer-actions" :class="{pB30: isFullSucreen}" v-if="list.length">
      <view class="u-flex">
        <view class="u-flex-1 footer-btn" @click="uploadImg">上传物料图片</view>
      </view>
    </view>
    <u-picker :show="pickerType!=''" :columns="[pickerInfo[pickerType]]" keyName="name" @confirm="pickerConfirm" @cancel="pickerType = ''"></u-picker>
    <u-overlay :show="overlayShow" @click="overlayShow = false">
			<image class="overlayImage" :src="overlayImg" mode="widthFix"></image>
			<view class="saveBase" @click="saveBase">保存图片</view>
		</u-overlay>
  </view>
</template>

<script>
import { getExecuteServiceAll, getExecuteServiceImg, getBaseImg, getExecuteSaveImage, UploadFile } from '@/api/index'

export default {
  data() {
		return {
      isFullSucreen: this.isFullSucreen,
      searchValue: '000024',
      pickerType: '',
      pickerInfo: {
         type: [
          {
            id: 'Materidal',
            name: '物料编码'
          },
          {
            id: 'MaterialName',
            name: '物料名称',
          },
          {
            id: 'ModelName',
            name: '规格型号'
          },
        ],
      },
      form: {
        typeName: '物料编码',
        type: 'Materidal',
      },
      orgId: '',
      list: [],
      listIndex: 0,
      overlayShow: false,
      overlayImg: '',
    }
  },
  async onLoad(options) {
    this.orgId = options.orgId
  },
  methods: {
    uploadImg() {
      const that = this
      uni.chooseMedia({
        count: 1,
        mediaType: ['image'],
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        maxDuration: 30,
        camera: 'back',
        success(res) {
          wx.getFileSystemManager().readFile({
            filePath: res.tempFiles[0].tempFilePath, //要读取的文件的路径 (本地路径)
            encoding: "base64", //指定读取文件的字符编码，如果不传 encoding，则以 ArrayBuffer 格式读取文件的二进制内容
            async success(res) {
              const parameters = { "data": { "FileName": that.list[that.listIndex].FmaterialNumber+'.png', "IsLast": true, "SendByte": res.data } }
              uni.showLoading({ mask: true });
              const resUpload = await UploadFile(parameters)
              uni.hideLoading()
              if(resUpload.Result && resUpload.Result.FileId) {
                await getExecuteSaveImage({json: JSON.stringify({ MaterialNumber: that.list[that.listIndex].FmaterialNumber, Fileid: resUpload.Result.FileId })})
                uni.hideLoading()
                uni.showToast({
                  title: '上传成功',
                  icon: 'none',
                })
              } else {
                uni.showToast({
                  title: '图片上传服务器失败',
                  icon: 'none',
                })
              }
            }
          })
        }
      })
    },
    getForm() {
      if(this.searchValue.trim()!== '') {
        uni.showLoading({ mask: true });
        // 物料编码：Materidal。规格型号：ModelName。物料名称：MaterialName
        const parameters = {
          Materidal: '',
          ModelName: '',
          MaterialName: '',
          orgNumber: this.orgId
        }
        if(this.form.type == 'Materidal') {
          parameters.Materidal = this.searchValue
        } else if(this.form.type == 'MaterialName') {
          parameters.MaterialName = this.searchValue
        } else {
          parameters.ModelName = this.searchValue
        }
        getExecuteServiceAll({json: JSON.stringify(parameters)}).then(res => {
          uni.hideLoading()
          if(res.Material.length && res.Material[0].IsSuccess !=='false') {
            this.list = res.Material
            this.listIndex = 0
          } else {
            uni.showToast({
              icon: 'none',
              title: '无数据',
            })
          }
        })
      } else {
        uni.showToast({
          title: '请输入内容',
          icon: 'none'
        });
      }
    },
    search() {
      this.getForm()
    },
    pickerConfirm(e) {
      if(e.value[0].id) {
        this.form[this.pickerType] = e.value[0].id
        this.form[this.pickerType+'Name'] = e.value[0].name
      } else {
        this.form[this.pickerType] = ''
        this.form[this.pickerType+'Name'] = ''
      }
      this.pickerType = ''
    },
    imageBig(idCode) {
      uni.showLoading({ mask: true });
      getExecuteServiceImg({ "parameters": [ {"MaterialNumber": idCode, "token": uni.getStorageSync('token')} ]}).then(res => {
        function getQueryParam(url, param) {
          // 构造正则表达式，匹配 ? 或 & 后面跟随的参数名称和其值
          const regex = new RegExp('[?&]' + param + '=([^&#]*)', 'i');
          const result = regex.exec(url);
          return result ? decodeURIComponent(result[1]) : null;
        }
        getBaseImg({ "parameters": [ {"FileId": getQueryParam(res.Url, 'fileId'), "StartIndex": 0 } ]}).then(bres => {
          if(bres.Result.FilePart) {
            uni.hideLoading();
            this.overlayImg = 'data:image/png;base64,' + bres.Result.FilePart
            this.overlayShow = true
          } else {
            uni.showToast({
              title: "暂无图片",
              icon: 'none'
            });
          }
        })
      })
    },
    saveBase64ToPhotoAlbum(base64Data) {
      // 1. 去除Base64头部信息（如："data:image/png;base64,"）
      const base64 = base64Data.replace(/^data:image\/\w+;base64,/, '');
      // 2. 转换为ArrayBuffer
      const arrayBuffer = uni.base64ToArrayBuffer(base64);
      // 3. 生成临时文件路径
      const filePath = `${wx.env.USER_DATA_PATH}/temp_${Date.now()}.png`;
      // 4. 写入文件
      const fs = uni.getFileSystemManager();
      return new Promise((resolve, reject) => {
        fs.writeFile({
        filePath,
        data: arrayBuffer,
        encoding: 'binary',
        success: () => {
          // 5. 保存到相册
          uni.saveImageToPhotosAlbum({
            filePath,
            success: () => resolve('保存成功'),
            fail: (err) => reject('保存失败，请检查权限：' + err.errMsg),
          });
        },
        fail: (err) => reject('文件写入失败：' + err.errMsg),
        });
      });
    },
    async saveBase() {
      try {
        uni.showLoading({ mask: true });
        const base64 = this.overlayImg;
        await this.saveBase64ToPhotoAlbum(base64);
        uni.hideLoading()
        uni.showToast({ title: '保存成功', icon: 'success' });
        console.error("保存图片成功");
      } catch (error) {
        console.error("保存图片失败 error：", error);
        uni.showToast({ title: error, icon: 'none' });
        // 处理权限被拒绝的情况
        if (error.includes('authorize')) {
        uni.openSetting({}); // 引导用户打开权限设置
        }
      }
    },
  }
}
</script>

<style lang="less" scoped>
.page {
  width: 100%;
  min-height: 100vh;
  background: #f2f2f2;
  padding:0 0 188rpx;
  .search {
    padding: 16rpx 20rpx;
    background: #FFF;
    box-shadow: 3rpx 3rpx 4rpx rgba(0, 0, 0, 0.16);
    display: flex;
    align-items: center;
    .search-type {
      width: 180rpx;
      margin-right: 10rpx;
      font-size: 28rpx;
      display: flex;
      align-items: center;
      gap: 6rpx;
    }
  }
  .box {
    margin-top: 20rpx;
    padding: 16rpx 20rpx;
    background: #FFF;
    border-radius: 20rpx;
    box-shadow: 3rpx 3rpx 4rpx rgba(0, 0, 0, 0.16);
    display: flex;
    align-items: center;
    justify-content: flex-start;
  }
  .goods-title {
    padding: 20rpx 30rpx;
    background: #f0f0f0;
    font-size: 32rpx;
    font-weight: bold;
    display: flex;
  }
  .goods-info {
    padding: 20rpx 30rpx;
    background: #fff;
  }
  .footer-actions {
    border-top: 2rpx solid #d6d7d9;
    background: linear-gradient(90deg, #2979ff 0%, #7D9EF8 100%);
    position: fixed;
    bottom: 0;
    width: 100%;
    .footer-btn {
      display: flex;
      justify-content: center;
      align-items: center;
      color: #FFF;
      height: 90rpx;
    }
  }
}
.overlayImage {
  width: 80%;
  height: auto;
  margin: 300rpx auto 50rpx;
}
.saveBase {
  width: 200rpx;
  height: 60rpx;
  line-height: 60rpx;
  color: #fff;
  background-color: #2677f0;
  text-align: center;
  border-radius: 50rpx;
  margin: 0 auto;
}
</style>
